package com.qf.fmall2302.order.service.impl;

import com.qf.fmall2302.order.entity.OrderItem;
import com.qf.fmall2302.order.entity.Orders;
import com.qf.fmall2302.order.mapper.OrdersMapper;
import com.qf.fmall2302.order.service.IOrderItemService;
import com.qf.fmall2302.order.service.IOrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.fmall2302.product.entity.ProductSku;
import com.qf.fmall2302.product.mapper.ProductSkuMapper;
import com.qf.fmall2302.shopcart.entity.ShoppingCart;
import com.qf.fmall2302.shopcart.service.IShoppingCartService;
import com.qf.fmall2302.utils.FmallConstants;
import com.qf.fmall2302.utils.OrderConstants;
import com.qf.fmall2302.wxpay.WxPayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单  服务实现类
 * </p>
 *
 * @author dongjl
 * @since 2023-08-24
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {

    @Autowired
    IShoppingCartService shoppingCartService;

    @Autowired
    IOrderItemService orderItemService;

    @Autowired
    ProductSkuMapper productSkuMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public synchronized HashMap<String, Object> addOrder(Integer[] cids, Orders orders) throws Exception {

        //1. 查询用户购物车中的对应的商品套餐库存量是否还足够
        List<ShoppingCart> shoppingCarts = checkAndCutStock(cids);

        //2. 生成唯一的订单编号
        String orderId = UUID.randomUUID().toString().replaceAll("-", "");

        //3. 生成订单主表（orders表）中的数据
        orders.setOrderId(orderId);
        // 产品名称：untitled ,商品1，商品2
        // List<ShoppingCart> ---> List<商品名称>
        String productNames= shoppingCarts.stream()
                .map(ShoppingCart::getProductName)
                .distinct()
                .collect(Collectors.joining(","));
        orders.setUntitled(productNames);

        // 订单的状态，初始值1，待付款 status
        orders.setStatus(OrderConstants.ORDER_STATUS_NOTPAY);
        // 逻辑删除状态，初始值为0 delete_status
        orders.setDeleteStatus(FmallConstants.NOT_DELETED);
        Date date = new Date();
        orders.setCreateTime(date);
        orders.setUpdateTime(date);

        this.save(orders);  // 把订单数据保存到 orders表中

        ArrayList<OrderItem> orderItems = new ArrayList<>();
        //4. 生成订单明细表的数据 （OrderItem表）
        for (ShoppingCart shoppingCart : shoppingCarts) {

            // 对于每个 shoppingCart 对象，生成一个 订单明细对象，存入订单明细表中
            OrderItem orderItem = new OrderItem();
            String orderItemId = UUID.randomUUID().toString().replaceAll("-", "");
            orderItem.setItemId(orderItemId);
            // 设置该订单明细关联的订单对象
            orderItem.setOrderId(orderId);

            // 购物车中的商品添加日期
            String cartTime = shoppingCart.getCartTime();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date cartDate = simpleDateFormat.parse(cartTime);
            orderItem.setBasketDate(cartDate);
            orderItem.setIsComment(0);
            orderItem.setBuyCounts(Integer.valueOf(shoppingCart.getCartNum()));

            // 如果一个对象的属性跟另外一个对象的属性同名，如何进行同名属性的值的拷贝？
            BeanUtils.copyProperties(shoppingCart,orderItem);

//            orderItem.setProductId(shoppingCart.getProductId());
//            orderItem.setProductImg(shoppingCart.getProductImg());
//            orderItem.setProductName(shoppingCart.getProductName());
//            orderItem.setProductPrice(shoppingCart.getProductPrice());
//            orderItem.setSkuId(shoppingCart.getSkuId());
//            orderItem.setSkuName(shoppingCart.getSkuName());

            // 商品的购买的数量乘以商品的价格
            BigDecimal totalAmout = new BigDecimal(orderItem.getBuyCounts())
                    .multiply(orderItem.getProductPrice());
            orderItem.setTotalAmount(totalAmout);

            orderItems.add(orderItem);
        }

        //5. 保存订单到数据库
        orderItemService.saveBatch(orderItems); // 使用mp提供的批量保存方法，把数据保存到 order_item 表中

        //情况购物车中的对应的商品信息
        shoppingCartService.removeBatchByIds(Arrays.asList(cids)); // 使用mp提供的根据id批量删除方法

        //6. 跟微信支付平台交互，获取可以支付的url
        String payUrl = WxPayUtils.getPayUrl(orderId, productNames, orders.getActualAmount().longValue());

        //7. 组织返回的map数据
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("orderId",orderId);
        hashMap.put("productNames",productNames);
        hashMap.put("payUrl",payUrl);

        return hashMap;
    }

    @Override
    public String status(String orderid) {

        //1. 调微信支付的查询订单状态接口，获取订单状态
        String status =  WxPayUtils.queryStatus(orderid);

        //2. 如何支付成功了，需要修改订单表 中的 订单状态 和 支付时间
        if (status.equals("SUCCESS")){
            Orders orders = new Orders();
            orders.setOrderId(orderid);
            orders.setStatus("2");

            this.updateById(orders);
            return "2";

        }
        return "-1";
    }

    private List<ShoppingCart> checkAndCutStock(Integer[] cids) throws Exception {

        // 遍历每个购物车中的商品信息，判断库存是否足够，如果够就扣减库存，否则抛出异常
        List<ShoppingCart> shoppingCarts = shoppingCartService.listByCids(cids);

        for (ShoppingCart shoppingCart : shoppingCarts) {
            // 购物车中购买的数量
            String cartNum = shoppingCart.getCartNum();
            // 查询该商品库存量
            ProductSku productSku = productSkuMapper.selectById(shoppingCart.getSkuId());
            Integer stock = productSku.getStock();
            if (Integer.valueOf(cartNum)<=stock) {
                productSku.setStock(stock-Integer.valueOf(cartNum));
                // 更新数据库
                productSkuMapper.updateById(productSku);

            }else {
                throw new Exception(productSku.getSkuName()+":库存不足!");
            }

        }

        return shoppingCarts;

    }
}
